package util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * A class for handling configurations. Currently the configurations are that
 * follows:
 * 
 * Lap Time Sort After Display Only Amount of Stages Special Stages Stage
 * Difficulty File path Filename Contestant classes allowed Minimum Time to
 * Complete Stage
 * 
 * @author team07
 * 
 */
public class Configuration {
	
	public static final String COMPETITION_TYPE = "Competition Type";
	public static final String MAXTIME = "Maxtime";
	public static final String MIN_LAP_TIME = "Min Lap Time";
	

	protected static final Properties configuration = new Properties();
	protected static final Properties defaults = new Properties();
	public static final String CONFNAMESINIT = "configuration.xml";
	



	/**
	 * Loads Properties conf from XML
	 * 
	 * @param path
	 *            the specified filepath
	 * @throws IOException
	 *             exception thrown if the file doesn't exist or if access to it
	 *             was denied
	 */
	public static void loadFromXML(String path) throws IOException {
		
		InputStream inputStream = new FileInputStream(path);
		try{
			configuration.loadFromXML(inputStream);
		} finally{
			inputStream.close();
		}
	}

	/**
	 * Returns the string of the configuration-key
	 * 
	 * @param key
	 *            The specified key
	 * @return The String of the configuration key
	 * @throws IOException If the key does not exists
	 */
	public static String get(String key) throws IOException {
		defaults.setProperty(MAXTIME, "0");
		defaults.setProperty(COMPETITION_TYPE, "lap");
		defaults.setProperty(MIN_LAP_TIME, "15");
		
		String retVal = configuration.getProperty(key);
		if (retVal == null) {
			String retVal2 = defaults.getProperty(key);
			if(retVal2 == null){
				throw new IOException("Configuration entry does not exist: " + key);
			}
			return retVal2;
		}
		return retVal;
	}


}